<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/6/19
 * Time: 15:55
 */

namespace app\admin\controller;


use think\Db;
use think\Request;

class Aftersale extends Books
{
    /**
     * 待审核售后列表
     * @return mixed|\think\response\Json
     */
    public function checkIndex(){
        if(request()->isAjax()){
            $update_start = input('update_start');
            $update_end = input('update_end');
            $oi_good_name = input('keyword');
            $oi_after_status = input('oi_after_status');
            $after_user_num = input('after_user_num');//用户物流单号 暂不用
            $where = [];
            $where['oi_after_status'] = ['neq', 1];
            $where['after_status'] = 1;
            //申请日期
            if(isset($update_start) && $update_start != '' && isset($update_end) && $update_end != ''){
                $where['after_time'] = ['between', [$update_start, $update_end]];
            }
            if(isset($update_start) && $update_start != '' && isset($update_end) && $update_end == ''){
                $where['after_time'] = ['>=', $update_start];
            }
            if(isset($update_start) && $update_start == '' && isset($update_end) && $update_end != ''){
                $where['after_time'] = ['<=', $update_end];
            }
            //商品名称
            if(isset($oi_good_name) && $oi_good_name != ''){
                $where['oi_good_name'] = ['like', '%' . $oi_good_name . '%'];
            }
            //用户物流单号
//            if(isset($after_user_num) && $after_user_num != ''){
//                $where['after_user_num'] = ['like', '%' . $after_user_num . '%'];
//            }
            //售后类型
            if(isset($oi_after_status) && $oi_after_status != ''){
                $where['oi_after_status'] = $oi_after_status;
            }
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            // 获取总条数
            $count = Db::name('order_info')
                ->join('up_exchange ue', 'ue.exchange_id = after_exchange_id', 'left')
                ->join('up_return ur', 'ur.exchange_id = after_return_id', 'left')
                ->join('up_u_user', 'oi_user_id = user_id', 'left')
                ->where($where)
                ->count();
            $lists = Db::name('order_info')
                ->join('up_exchange ue', 'ue.exchange_id = after_exchange_id', 'left')
                ->join('up_return ur', 'ur.exchange_id = after_return_id', 'left')
                ->join('up_u_user', 'oi_user_id = user_id', 'left')
                ->field('oi_good_name, oi_price, oi_type, oi_num, oi_after_status, ur.exchange_name as return_name,
                ue.exchange_name, after_reason, after_num, after_time, user_username, after_spec_id, oi_id, 
                after_user_courier, after_user_num, after_us_courier, after_us_num, oi_spec_id, 
                oi_good_id, after_order_num')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('after_time desc')
                ->select();
            foreach ($lists as $key => $vo){
                if($vo['oi_type'] ==1){ //非图书
//                    if($vo['after_spec_id'] == ''){ //没有规格
//                        $spec = Db::table('up_good_spec')
//                            ->where('spec_id', $vo['oi_spec_id'])
//                            ->field('spec_name, spec_stock')
//                            ->find();
//                    }else{
                        $spec = Db::table('up_good_spec')
                            ->where('spec_id', $vo['after_spec_id'])
                            ->field('spec_name, spec_stock')
                            ->find();
//                    }
                    $lists[$key]['ISBN'] = '';
                    $lists[$key]['spec_stock'] = $spec['spec_stock'];
                    $lists[$key]['spec_name'] = $spec['spec_name'];
                }else{
                    $goodInfo = Db::table('up_goods')
                        ->field('good_isbn, good_stock')
                        ->where('good_id', $vo['oi_good_id'])
                        ->find();
                    $lists[$key]['ISBN'] = $goodInfo['good_isbn'];
                    $lists[$key]['spec_stock'] = $goodInfo['good_stock'];
                    $lists[$key]['spec_name'] = '';
                }
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        return $this->fetch('aftersale/checkindex');
    }
    
    /**
     * 同意售后
     * @return mixed|\think\response\Json
     */
    public function confirmAfter(){
        if(Request::instance()->isPost()){
            $id = input('oi_id');
            $oi_is_return = input('oi_is_rerturn');
            //=========  如果是换货，则需判断新规格的库存
            $orderInfo = Db::table('up_order_info')
                ->field('oi_after_status, oi_num, after_spec_id, oi_spec_id, oi_type, oi_good_id, oi_user_id, 
                oi_order_id')
                ->where('oi_id', $id)
                ->find();
            if($orderInfo['oi_after_status'] == 3){
                if($orderInfo['oi_type'] == 2){ //图书
                    $spec_stock = Db::table('up_goods')->where('good_id', $orderInfo['oi_good_id'])->value('good_stock');
                    if($spec_stock < $orderInfo['oi_num']){
                        return json(['code' => 100, 'msg' => '需换货的库存小于换货数量，不允许同意']);
                    }
                }else{
                    $spec_stock = Db::table('up_good_spec')->where('spec_id', $orderInfo['after_spec_id'])->value('spec_stock');
                    if($spec_stock < $orderInfo['oi_num']){
                        return json(['code' => 100, 'msg' => '需换货的库存小于换货数量，不允许同意']);
                    }
                }
                
            }
            Db::startTrans();
            try{
                //原规格是否存在,如果存在则释放库存
                $isHave = Db::table('up_good_spec')->where('spec_id', $orderInfo['oi_spec_id'])->find();
                if($isHave){
                    Db::table('up_good_spec')
                        ->where('spec_id', $orderInfo['oi_spec_id'])
                        ->setInc('spec_stock', $orderInfo['oi_num']);
                }
                
                if($orderInfo['oi_after_status'] == 3){ //换货，加减库存
                    //减新规格库存
                    Db::table('up_good_spec')
                        ->where('spec_id', $orderInfo['after_spec_id'])
                        ->setDec('spec_stock', $orderInfo['oi_num']);
                    
                    $str = '平台同意您的换货申请';
                    $after_status = 2;
                }else{
                    $str = '平台同意您的退货申请';
                    $after_status = 4;
                }
                
                $data = [
                    'ast_after_oi_id' => $id,
                    'ast_after_time' => date('Y-m-d H:i:s'),
                    'ast_after_content' => $str
                ];
                $update = [
                    'oi_is_rerturn' => $oi_is_return, //是否需要回寄  1 要  2 不要
                    'after_status' => $after_status,  //售后状态
                    'after_allow_time' => date('Y-m-d H:i:s') //平台确认同意时间
                ];
                //更新订单详情表
                Db::table('up_order_info')->where('oi_id', $id)->update($update);
                //插入时间轴表
                Db::table('up_after_sale_time')->insert($data);
                //修改订单表状态
                Db::table('up_order')->where('order_id', $orderInfo['oi_order_id'])->setField('order_after', 3);
                Db::commit();
                $res = 1;
            }catch(\Exception $e){
                Db::rollback();
                $res = 2;
            }
            if($res == 1){
                $user_id = (string)$orderInfo['oi_user_id'];
                $str_send = '喵喵阅读：您有一笔售后申请已审核通过，请及时查看';
                try{
                    $this->Jpush(1, $user_id, $str_send, ['send_type' => 6,'oi_id' => $id, 'oi_is_rerturn' => $oi_is_return, 'oi_after_status' => $orderInfo['oi_after_status']]);
                }catch(\Exception $e){
                }
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
            
        }
        $oi_id = input('oi_id');
        $order_id = Db::table('up_order_info')->where('oi_id', $oi_id)->value('oi_order_id');
        $after_status = Db::table('up_order')->where('order_id', $order_id)->value('order_status');
        $this->assign([
            'oi_id' => $oi_id,
            'after_status' => $after_status
        ]);
        return $this->fetch('aftersale/confirmafter');
    }
    
    /**
     * 拒绝售后
     * @return mixed|\think\response\Json
     */
    public function refuseAfter(){
        if(Request::instance()->isPost()){
            $id = input('oi_id');
            $after_false_reason = input('after_false_reason');//拒绝原因
            $orderInfo = Db::table('up_order_info')
                ->field('oi_after_status, oi_user_id, oi_order_id')
                ->where('oi_id', $id)
                ->find();
            if($orderInfo['oi_after_status'] == 3){ //换货
                $str = '平台拒绝了您的换货申请，拒绝原因：' . $after_false_reason;
            }else{
                $str = '平台拒绝了您的退货申请，拒绝原因：' . $after_false_reason;
            }
            $update = [
                'after_status' => 3,//拒绝
                'after_false_reason' => $after_false_reason
            ];
            $data = [
                'ast_after_oi_id' => $id,
                'ast_after_time' => date('Y-m-d H:i:s'),
                'ast_after_content' => $str
            ];
            Db::startTrans();
            try{
                //更新订单详情表
                Db::table('up_order_info')->where('oi_id', $id)->update($update);
                //插入时间轴表
                Db::table('up_after_sale_time')->insert($data);
                
                Db::commit();
                $res = 1;
            }catch(\Exception $e){
                Db::rollback();
                $res = 2;
            }
            if($res == 1){
                $user_id = (string)$orderInfo['oi_user_id'];
                $str_send = '喵喵阅读：您有一笔售后申请已被平台拒绝，请及时查看';
                try{
                    $this->Jpush(1, $user_id, $str_send, ['send_type' => 7,'oi_id' => $id, 'oi_after_status' => $orderInfo['oi_after_status'], 'after_status' => 3, 'order_id' => $orderInfo['oi_order_id']]);
                }catch(\Exception $e){
                }
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
        $oi_id = input('oi_id');
        $this->assign([
            'oi_id' => $oi_id
        ]);
        return $this->fetch('aftersale/refuseafter');
    }
}